package club.pinea.handler.lobby;

import club.pinea.annotations.Head;
import club.pinea.interfaces.TCPMessage;
import club.pinea.mapper.RoomMapper;
import club.pinea.model.Room;
import club.pinea.proto.BasicProto;
import club.pinea.proto.CommandProto;
import club.pinea.proto.GameProto;
import club.pinea.proto.LobbyProto;
import club.pinea.send.MessageSend;
import club.pinea.session.GlobalServerPlayerContainer;
import club.pinea.session.IOSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 进入游戏的身份验证
 */
@Head(CommandProto.Command.C_S_ROOM_AUTH_VALUE)
@Component
public class GameAuthHandler implements TCPMessage<BasicProto.BaseMessage> {

    @Resource
    private RoomMapper roomMapper;


    @Override
    public void doMessage(BasicProto.BaseMessage msg, IOSession session) throws Exception {
        LobbyProto.GameAuthRequest request = LobbyProto.GameAuthRequest.parseFrom(msg.getBody());
        // 调用Global的登录逻辑
        GlobalServerPlayerContainer.playerLogin(session, request.getUserId(), request.getToken());

        List<Room> rooms = roomMapper.queryAll(new Room());
        List<LobbyProto.Room> roomList = new ArrayList<>(rooms.size());
        rooms.forEach(r -> {
            LobbyProto.Room room = LobbyProto.Room.newBuilder()
                    .setRoomId(r.getRoomId())
                    .setMultiplyPower(r.getMultiplyPower())
                    .setSeatCount(r.getSeatCount())
                    .setRoomName(r.getRoomName())
                    .setRoomDesc(r.getRoomDesc())
                    .build();
            roomList.add(room);
        });

        LobbyProto.GameAuthResponse response = LobbyProto.GameAuthResponse.newBuilder()
                .setRes(MessageSend.successRes())
                .addAllRooms(roomList)
                .build();
        MessageSend.sendToUser(response, session);
    }
}
